package com.sh3h.generator.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import com.sh3h.generator.web.domain.GenDataSource;
import com.sh3h.generator.web.domain.query.entity.TableQuery;
import com.sh3h.generator.web.dtos.GenDataSourcesDto;
import com.sh3h.generator.web.dtos.Result;
import com.sh3h.generator.web.entity.TableEntity;
import com.sh3h.generator.web.service.impl.GenDatasourceServiceImpl;
import com.sh3h.generator.web.utils.GenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping({"/api/gen/datasources"})
public class DataSourceController {

    @Autowired
    private GenDatasourceServiceImpl datasourceService;

    @GetMapping("")
    public Result getByPage(int pageNum, int pageSize, String dbType, String connName) {
        Page<GenDataSource> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<GenDataSource> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isNullOrEmpty(dbType)) {
            queryWrapper.eq(GenDataSource::getDbType, dbType);
        }
        if (!StringUtils.isNullOrEmpty(connName)) {
            queryWrapper.like(GenDataSource::getConnName, connName);
        }
        Page<GenDataSource> datasourceList = datasourceService.page(page, queryWrapper);
        return Result.success(datasourceList);
    }

    @GetMapping("/all")
    public Result getAll() {
        List<GenDataSource> datasourceList = datasourceService.list();
        return Result.success(datasourceList);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") String id) {
        GenDataSource datasource = datasourceService.getById(id);
        return Result.success(datasource);
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable("id") String id) {
        Boolean result = datasourceService.removeById(id);
        return Result.success(result);
    }

    @PutMapping("/{id}")
    public Result updateById(@RequestBody GenDataSourcesDto dto) {
        GenDataSource datasource = GenDataSourcesDto.ToModal(dto);
        Boolean result = datasourceService.updateById(datasource);
        return Result.success(result);
    }

    @PostMapping("")
    public Result insert(@RequestBody GenDataSourcesDto dto) {
        GenDataSource datasource = GenDataSourcesDto.ToModal(dto);
        Boolean result = datasourceService.save(datasource);
        return Result.success(result);
    }

    @PostMapping("/test")
    public Result test(@RequestBody GenDataSourcesDto dto) {
        String driver = "";
        switch (dto.getDbType()) {
            case "MySql":
                driver = "com.mysql.jdbc.Driver";
                break;
            case "SqlServer":
                driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                break;
        }

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            return Result.error(500, e.getMessage());
        }

        try {
            DriverManager.getConnection(dto.getConnUrl(), dto.getUsername(), dto.getPassword());
        } catch (SQLException e) {
            return Result.error(500, e.getMessage());
        }
        return Result.success(true);
    }

    @GetMapping("/{dataSrouceId}/tables")
    public Result getAllTables(@PathVariable("dataSrouceId") String dataSourceId) throws SQLException, ClassNotFoundException {
        GenDataSource datasource = datasourceService.getById(dataSourceId);
        TableQuery tq = new TableQuery(datasource);
        List<TableEntity> datasourceList = GenUtils.getTableList(tq);
        datasourceList.forEach(a->a.setDataSourceId(dataSourceId));
        return Result.success(datasourceList);
    }

//    @GetMapping("/{dataSrouceId}/tables/{tableId}/fields")
//    public Resp getAllTables(@PathVariable("dataSrouceId") String dataSourceId, @PathVariable("tableId") String tableId) {
//        GenDataSource datasource = datasourceService.getById(dataSourceId);
//        TableQuery tq = new TableQuery(datasource);
//        List<GenTable> datasourceList = GenUtils.getTableFieldList(tq, tableId);
//        return Resp.success(datasourceList);
//    }
}
